extends Node

@export var default_fps: int = 60
const MIN_FPS := 30
const MAX_FPS := 120
const CONFIG_PATH := "user://settings.cfg"
const CONFIG_SECTION := "video"
const CONFIG_KEY := "target_fps"

func _ready():
	add_to_group("frame_rate_manager")
	var saved := _load_saved_fps()
	if saved <= 0:
		_apply_fps(_clamp_fps(default_fps))
	else:
		_apply_fps(_clamp_fps(saved))

func set_target_fps(fps: int) -> void:
	# 对外接口：设置并保存帧率
	var clamped := _clamp_fps(fps)
	_apply_fps(clamped)
	_save_fps(clamped)

func increase_fps(step: int = 10) -> void:
	set_target_fps(Engine.max_fps + step)

func decrease_fps(step: int = 10) -> void:
	set_target_fps(Engine.max_fps - step)

func _apply_fps(fps: int) -> void:
	Engine.max_fps = fps

func _clamp_fps(fps: int) -> int:
	return clamp(fps, MIN_FPS, MAX_FPS)

func _load_saved_fps() -> int:
	var cfg := ConfigFile.new()
	var err := cfg.load(CONFIG_PATH)
	if err != OK:
		return -1
	return int(cfg.get_value(CONFIG_SECTION, CONFIG_KEY, -1))

func _save_fps(fps: int) -> void:
	var cfg := ConfigFile.new()
	cfg.load(CONFIG_PATH)
	cfg.set_value(CONFIG_SECTION, CONFIG_KEY, fps)
	cfg.save(CONFIG_PATH)
